package cn.jbolt.config.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.stereotype.Component;
import cn.jbolt.util.Result;



@Aspect
@Component
public class ResultErrorAspect {
    @Around("@annotation(org.springframework.transaction.annotation.Transactional)")
    public Object aroundTransaction(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result = null;
        try {
            result = joinPoint.proceed();
            // 检查返回结果，判断是否需要回滚
            if (shouldRollback(result)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        } catch (Exception e) {
            // 发生异常时也可以根据情况回滚
            if (shouldRollbackOnException(e)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            throw e;
        }
        return result;
    }

    private boolean shouldRollback(Object result) {
        // 根据业务逻辑判断是否需要回滚
        // 示例：假设 result 是一个自定义的 Result 对象，isError 表示是否出错
        return result instanceof Result && ((Result) result).isError();
    }

    private boolean shouldRollbackOnException(Exception e) {
        // 根据异常类型判断是否需要回滚
        return true; // 这里可以根据实际情况调整
    }
}